import { Component, OnInit } from '@angular/core'
import { JsonApiService } from 'app/core/api/json-api.service' //http请求配置引入
import { Router, ActivatedRoute } from '@angular/router' //路由引入
import { config } from '../../shared/smartadmin.config'

declare var $: any
@Component({
  selector: 'sa-project-leader',
  templateUrl: './project-leader.component.html'
})
export class ProjectLeaderComponent implements OnInit {
  tableData: any[] = [] //table数据
  totalCount: number = 0 //分页总条数
  curPage: number = 1 //分页当前页
  pageSize: number = 10 //内置的分页每页条数
  companyArrays: any[] = []

  CorporateAccountFrom: any = {
    companyArr: [],
    name: '',
    userId: '',
    remark: ''
  }

  tableSearch: any = {
    companyId: '',
    name: ''
  }
  paramFormat: any = {
    id: 'id',
    text: 'name'
  }
  companyList: any = []

  startTime: string = ''
  endTime: string = ''
  editStatus: boolean = false
  companyText: string = ''

  constructor(private jsonApiService: JsonApiService, private router: Router, private activatedRoute: ActivatedRoute) {
    activatedRoute.queryParams.subscribe(queryParams => {})
  }

  //对接厂区回调
  addCompanySelected(data) {
    this.CorporateAccountFrom.companyArr = data.companyIdSelectedList
  }

  //厂区选中回调
  companySelected(data) {
    this.tableSearch.companyId = data.companyId
    // this.tableSearch.companyName = data.companyName;
  }

  //负责人选中
  optionSelectedForm(data) {
    this.CorporateAccountFrom.userId = data.id
    this.CorporateAccountFrom.name = data.text
  }

  // 列表筛选负责人选中
  optionTableSearch(data) {
    this.tableSearch.name = data.text
  }

  ngOnInit() {
    this.load()
    this.getCompanyList()
    this.initDate()
  }
  //table刷新
  refresh() {
    this.load()
  }
  //表格搜索
  table_search() {
    this.curPage = 1
    this.load()
  }
  //初始化加载list数据
  load() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      parameters: this.tableSearch
    }
    let reqdata = 'gridPager=' + JSON.stringify(data)
    this.jsonApiService.http('projectPeople/projectChargeList.html', reqdata).subscribe(data => {
      if (data.isSuccess) {
        this.tableData = data.exhibitDatas
        this.totalCount = data.recordCount
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }

  // 运维负责人
  getCompanyList() {
    this.companyList = []
    this.jsonApiService.http_get('projectPeople/getOperationUserList.html').subscribe(data => {
      if (data.success) {
        this.companyList = data.data
      } else {
        this.jsonApiService.message(data.message)
      }
    })
  }

  //初始化日期
  //初始化时间
  initDate() {
    var that = this
    return new Promise(function (resolve, reject) {
      System.import('assets/js/datepicker/js/bootstrap-datetimepicker.min.js').then(() => {
        System.import('assets/js/datepicker/locales/bootstrap-datetimepicker.zh-CN.js').then(() => {
          $('#datetimepicker1')
            .datetimepicker({
              language: 'zh-CN',
              autoclose: true, //选择后自动关闭
              format: "yyyy-mm-dd hh:ii:ss",//日期格式
              weekStart: 1,
              startView: 2,
              minView:0
            })
            .on('changeDate', function (e) {
              const date = e.date;
              const time = common.getTimeMmss(date)
              that.startTime = time
              const limitDate = date.getTime() + (24*60*60*1000)*5
              $('#datetimepicker2').val('')
              $('#datetimepicker2').datetimepicker('setStartDate', common.getTimeMmss(new Date(that.startTime)))
              $('#datetimepicker2').datetimepicker('setEndDate', common.getTimeMmss(new Date(limitDate)))
            })
          $('#datetimepicker2')
            .datetimepicker({
              language: 'zh-CN',
              autoclose: true, //选择后自动关闭
              format: "yyyy-mm-dd hh:ii:ss",//日期格式
              weekStart: 1,
              startView: 2,
              minView:0
            })
            .on('changeDate', function (e) {
              const date = e.date;
              const time = common.getTimeMmss(date)
              that.endTime = time
              $('#datetimepicker1').datetimepicker('setEndDate', that.endTime)
            })
          resolve(null)
        })
      })
    })
  }

  //删除
  delRow(row) {
    this.jsonApiService.confirm_message('此操作将永久删除数据,确认要删除?').then(() => {
      this.jsonApiService
        .http_obj('projectPeople/delProjectCharge.html', {
          id: row.id
        })
        .subscribe(data => {
          this.jsonApiService.message(data.message)
          if (data.success) {
            this.load()
          }
        })
    })
  }

  //分页回调
  paginate(e) {
    this.curPage = e.page + 1
    this.pageSize = e.rows
    this.load()
  }
  /*
   * 新增
   */
  table_add(modal) {
    this.editStatus = false
    modal.show()
    this.resetForm()
  }
  // 编辑
  editRow(row, modal) {
    modal.show()
    this.editStatus = true
    this.companyText = row.companyName
    this.CorporateAccountFrom.id = row.id
    this.CorporateAccountFrom.companyArr = [row.companyId]
    $("#select2-leaderSelectId2-container").html('<span class="select2-selection__clear">×</span>' + row.name)
    this.CorporateAccountFrom.userId = row.userId
    this.CorporateAccountFrom.name = row.name
    this.CorporateAccountFrom.remark = row.remark
  }
  /*
   * 导出弹窗
   */
  table_export(modal) {
    modal.show()
    this.del_date()
  }
  // 清除时间选择
  del_date() {
    this.startTime = ''
    this.endTime = ''
    $('#datetimepicker1').val('').change()
    $('#datetimepicker2').val('').change()
    $('#datetimepicker2').datetimepicker('setStartDate', null)
    $('#datetimepicker2').datetimepicker('setEndDate', null)
    $('#datetimepicker1').datetimepicker('setEndDate', null)
  }
  // 未处理订单导出
  exportData(modal) {
    if(this.startTime && this.endTime) {
      const oneDay =  24*60*60*1000;
      const startTime = new Date(this.startTime).getTime();
      const endTime = new Date(this.endTime).getTime();
      // if((endTime - startTime <= oneDay) && (endTime - startTime > 0)){
        const url = 'projectPeople/exportExcel.html?startTime=' + this.startTime + '&endTime=' + this.endTime;
        window.location.href = config.BaseURL + url;
        modal.hide()
      // }else {
      //   this.jsonApiService.message('请选择1天内的导出时间段')
      // }
    }else {
      this.jsonApiService.message('请选择导出时间')
    }
  }
  // 数据导出
  tableExport() {
    let data = {
      pageSize: this.pageSize,
      nowPage: this.curPage,
      isExport: true,
      parameters: this.tableSearch
    }
    common.exprotDataFile(data, 'gridPager', config.BaseURL + 'projectPeople/projectChargeList.html')
  }
  /*
   * 关闭弹窗
   */
  modalClose(modal) {
    modal.hide()
    this.CorporateAccountFrom = {
      userId: '',
      name: '',
      companyArr: [],
      remark: ''
    }
    $('#leaderSelectId').val('').trigger('change')
    $('#leaderSelectId2').val('').trigger('change')
  }
  resetForm() {
    this.CorporateAccountFrom = {
      userId: '',
      name: '',
      companyArr: [],
      remark: ''
    }
    this.companyArrays = []
    $('#leaderSelectId').val('').trigger('change')
    $('#leaderSelectId2').val('').trigger('change')
  }
  /*
   * form提交
   */
  apiControlSubmit(modal) {
    if (this.CorporateAccountFrom.companyArr.length === 0) {
      this.jsonApiService.message('请选择负责厂区')
      return
    }
    if (!this.CorporateAccountFrom.userId) {
      this.jsonApiService.message('请选择负责人')
      return
    }
    this.CorporateAccountFrom.companyIds = this.CorporateAccountFrom.companyArr.join(',')
    try {
      this.editStatus ? '' : delete this.CorporateAccountFrom.id
    }catch {}
    const url = this.editStatus ? 'projectPeople/editProjectCharge.html' : 'projectPeople/addProjectCharge.html'
    this.jsonApiService.http_obj(url, this.CorporateAccountFrom).subscribe(data => {
      this.jsonApiService.message(data.message)
      if (data.success) {
        this.load()
        this.modalClose(modal)
      }
    })
  }
}
